﻿/// <reference path="../ext-3.0.0/ext-all.js" />
/// <reference path="../ext-3.0.0/adapter/ext/ext-base.js" />
/// <reference path="XMLOperation.js" />
/// <reference path="commonFun.js" />
/// <reference path="json2.js" />
/// <reference path="Window.js" />

/*
*   vml基本操作脚本
*/

/*
*   公共变量定义区
*/
var ToolBarOperper = null; //权限控制对象，由XML文件读取，主要用于工具条
//var MenuRightMouse = null; //操作对象，不同的资源有不同的属性显示，主要用于鼠标右键菜单
var AllObjects = null; //界面上所有的对象组
var xmlPath = '../OperationPermissions.xml'; //操作权限配置XML文件路径
var resourcetypeData = null; //资源类型数据

var win = null; //所有对象的属性 性能窗口    页面加载的时候创建,每次调用的时候初始化
/*
*   整体页面承载对象 页面对象容器
*/
function Group() {
    this.id = 'group'; //容器默认ID
    this.text = 'group'; //容器默认文本
    this.type = 'group'; //类型为容器
    this.count = 1; //容器中对象的数目
    this.mouseX = -1; //鼠标开始点横坐标
    this.mouseY = -1; //鼠标开始点纵坐标
    this.mouseEndX = -1; //鼠标结束点横坐标
    this.mouseEndY = -1; //鼠标结束点纵坐标
    this.reader = null; //用于显示机房基本性能
    this.items = null; //用于显示机房性能数据
    this.backgroundimage = ''; //机房背景图片
    this.room = null; //机房对象
    this.nodes = []; //容器中的点对象数组
    this.lines = []; //容器中线对象数组
    this.shapes = []; //多边形对象数组
    this.action = null; //容易操作记录
    this.selectedObj = []; //容器中选中对象数组
    this.contextMenuObj = null; //右键菜单主对象
    this.contextMenu = null; //鼠标右键菜单
    this.contextMenuOperation = null; //鼠标右键菜单操作对象数组  
    this.lineMirror = null; //监视容器中是否在画线
    this.init = function() {
        var group = _('group');
        group.setAttribute('container', this); //将对象添加到自己的属性中
        group.onmousedown = GroupEvent.mouseDown; //鼠标按下事件
        group.onmousemove = GroupEvent.mouseMove; //鼠标移动事件
        group.onmouseup = GroupEvent.mouseUp; //鼠标弹起事件
        group.onkeydown = GroupEvent.keyDown; //键盘按键按下事件
        group.onkeyup = GroupEvent.keyUp; //键盘按键弹起事件
        group.onclick = GroupEvent.click; //单击事件
        group.oncontextmenu = GroupEvent.onContextMenu; //右键菜单事件
        //创建监视线，用于画线时使用,需要初始化，并将其设置为隐藏
        //this.lineMirror = new Line();
    };
    //初始化界面所有的对象
    this.initChild = function() {
        if (AllObjects) { //如果AllObjects不为空
            var length = 0;
            if (AllObjects.nodes) {
                length = AllObjects.nodes.length;
                var node = null;
                for (var i = 0; i < length; i++) {
                    node = new Node(); //创建节点对象
                    node.initData(AllObjects.nodes[i]); //初始化节点对象基本数据
                    node.init(); //初始化节点对象
                    // this.nodes.push(node);
                }
                this.count = length;
            }
            if (AllObjects.lines) {
                length = AllObjects.lines.length;
                var line = null;
                for (var i = 0; i < length; i++) {
                    line = new Line(); //创建节点对象
                    line.initData(AllObjects.lines[i]); //初始化节点对象基本数据
                    line.init(); //初始化节点对象
                    //  this.lines.push(line);
                }
                this.count += length;
            }
            if (AllObjects.shapes) {
                length = AllObjects.shapes.length;
                var shape = null;
                for (var i = 0; i < length; i++) {
                    shape = new Shape();
                    shape.initData(AllObjects.shapes[i]);
                    shape.init();
                    // this.shapes.push(shape);
                }
                this.count += length;
            }
            this.setRoominfo(AllObjects.room);
            this.backgroundimage = '../Images/room/backimage/' + AllObjects.room.BACKGROUNDIMAGE; //设置机房的背景图片
            var g = _('group');
            if (this.backgroundimage.length > 25 && checkServerFile(this.backgroundimage)) {
                g.style.backgroundImage = "url('" + this.backgroundimage + "')"; //设置机房背景图片
            }
            else {
                g.style.backgroundImage = "url('../Images/room/backimage/2.png')"; //设置机房背景图片
            }
            document.title = AllObjects.room.ROOMNAME + '机房布局图';
            this.initDirection(AllObjects.room.DIRECTION);
            //g.style.backgroundPosition = "30px center";
            //初始化机房性能基本信息字段
            this.setItems();
            this.setReader();
        }
    };
    //显示方向标记
    this.initDirection = function(direction) {
        var group = _('group');
        var obj = null;
        var d = ["55,0,60,50,55,35,50,50,55,0", "80,25,50,45,60,45,60,55,80,25", "80,25,50,45,60,45,60,55,80,25", "105,50,55,55,70,50,55,45,105,50", "80,75,60,45,60,55,50,55,80,75", "80,75,60,45,60,55,50,55,80,75", "55,100,50,50,55,65,60,50,55,100", "25,75,50,45,50,55,60,55,25,75", "25,75,50,45,50,55,60,55,25,75", "5,50,55,45,40,50,55,55,5,50", "25,25,60,45,50,45,50,55,25,25", "25,25,60,45,50,45,50,55,25,25"]; //各点时钟方向
        createObj(obj = document.createElement('v:polyline'), { points: d[direction - 1], filled: 't', fillcolor: 'black' });
        obj.style.position = 'absolute';
        obj.style.left = group.offsetWidth;
        group.appendChild(obj);
        var txt = document.createElement('v:textbox');
        txt.innerText = '北';
        //obj.style.position = 'absolute';
        txt.className = 'vml_txt_direction';
        obj.appendChild(txt);
    }
    //组对象事件开始
    this.eventStart = function(e) {
        var e = e || 'down';
        var selNode = this.getEventNode(e); //获取事件点
        var selLine = this.getEventLine(); //获取事件线
        var shape = this.getEventShape(e);
        this.clearSelected(e); //清除所有选择对象
        if (shape) {
            if (e == 'down') {
                this.clearSelected();
                shape.setSelected();
                this.selectedObj = GroupEvent.insertObjInArr(this.selectedObj, shape);
            }
            else {
                shape.setMouseMove();
                shape.tipShow();
            }
        }
        if (selNode) {
            if (e == 'down') {
                if (!GroupEvent.isInArr(this.selectedObj, selNode)) {
                    this.clearSelected();
                    selNode.setSelected();
                    // selNode.tipShow();
                    this.selectedObj = GroupEvent.insertObjInArr(this.selectedObj, selNode);
                }
                if (this.lineFlag == null) {
                    this.action = 'nodedown';
                }
                else if (this.lineFlag != null) {
                    this.action = 'drawline';
                    this.drawMirrorLineFrom(selNode);
                }
            }
            else {
                selNode.setMouseMove();
                selNode.tipShow();
            }
        }
        else if (selLine) {
            for (var i = 0; i < selLine.length; i++) {
                if (!GroupEvent.isInArr(this.selectedObj, selLine[i])) {
                    selLine[i].setSelected();
                    this.selectedObj = GroupEvent.insertObjInArr(this.selectedObj, selLine[i]);
                }
            }
        }
    };
    //获取事件点
    this.getEventNode = function(direction) {
        var res = null;
        var nodeCount = this.nodes.length;
        var node = null;
        var x, y;
        switch (direction.toLowerCase()) {
            case 'down':
                x = this.mouseX;
                y = this.mouseY;
                break;
            case 'up':
                x = this.mouseEndX;
                y = this.mouseEndY;
                break;
            default:
                x = GroupEvent.getMouseX();
                y = GroupEvent.getMouseY();
                break;
        }
        for (var i = (nodeCount - 1); i >= 0; i--) {
            node = this.nodes[i];
            if (node.pointInObj(x, y)) {//判断坐标点在哪个节点对象上面
                res = node;
                break;
            }
        }
        return res;
    };
    //获取事件多边形
    this.getEventShape = function(direction) {
        var res = null;
        var shapeCount = this.shapes.length;
        var shape = null;
        var x, y;
        switch (direction.toLowerCase()) {
            case 'down':
                x = this.mouseX;
                y = this.mouseY;
                break;
            case 'move':
                x = this.mouseX;
                y = this.mouseY;
                break;
            case 'up':
                x = this.mouseEndX;
                y = this.mouseEndY;
                break;
            default:
                x = GroupEvent.getMouseX();
                y = GroupEvent.getMouseY();
                break;
        }
        for (var i = (shapeCount - 1); i >= 0; i--) {
            shape = this.shapes[i];
            if (shape.pointInObj(x, y)) {//判断坐标点在哪个节点对象上面
                res = shape;
                break;
            }
        }
        return res;
    };
    //获取事件线
    this.getEventLine = function() {
        var res = null;
        var lineCount = this.lines.length;
        var lin = null;
        var x = this.mouseX;
        var y = this.mouseY;
        var isStroke = -1;
        for (var i = (lineCount - 1); i >= 0; i--) {
            line = this.lines[i];
            if (line.pointInObj(x, y)) {
                if (res == null || line.obj.style.zIndex == '22') {
                    res = null;
                    res = GroupEvent.insertObjInArr(res, line);
                    isStroke = line.pointInStroke(x, y);
                    if (isFinite == 0) {
                        this.selectedLineTo = [];
                        this.selectedLineFrom = [];
                        this.selectedLineTo = GroupEvent.insertObjInArr(this.selectedLineTo, line);
                    }
                    else if (isStroke == 1) {
                        this.selectedLineTo = [];
                        this.selectedLineFrom = [];
                        this.selectedLineFrom = GroupEvent.insertObjInArr(this.selectedLineFrom, line);
                    }
                }
            }
        }
        return res;
    };
    //显示右键菜单
    this.setContextMenuShow = function() {
        //先将所有的对象的右键菜单销毁
        var length = this.nodes.length;
        for (var i = 0; i < length; i++) {
            this.nodes[i].destroyContextMenu(); //将所有选中的对象的右键菜单销毁
            this.nodes[i].cannelSelected();
        }
        length = this.shapes.length;
        for (var i = 0; i < length; i++) {
            this.shapes[i].destroyContextMenu(); //将所有选中的对象的右键菜单销毁
            this.shapes[i].cannelSelected();
        }
        this.contextMenuObj = null; //菜单右键对象清空
        var obj = this.selectedObj[0];
        if (obj) {
            obj.createContextMenu(); //创建右键菜单
            obj.showContextMenu(); //显示右键菜单
            this.contextMenuObj = obj;
            obj.setSelected();
        }
    };
    this.point = function(direction) {
        switch (direction.toLowerCase()) {
            case 'down':
                this.mouseX = GroupEvent.getMouseX();
                this.mouseY = GroupEvent.getMouseY();
                break;
            case 'move':
                this.mouseX = GroupEvent.getMouseX();
                this.mouseY = GroupEvent.getMouseY();
                break;
            case 'up':
                this.mouseEndX = GroupEvent.getMouseX();
                this.mouseEndY = GroupEvent.getMouseY();
                break;
        }
    };
    this.checkLine = function(fromObj, toObj) {
        var res = true;
        if (fromObj == toObj) {
            res = false;
        }
        var len = this.lines.length;
        var line = null;
        for (var i = 0; i < len; i++) {
            line = this.lines[i];
            if ((line.fromObj == fromObj) && (line.toObj == toObj)) {
                res = false;
                Ext.MessageBox.alert('警告', '两点之间已经存在连接!');
                break;
            }
        }
        return res;
    };
    //组选择对象清除
    this.clearSelected = function(e) {
        var length = this.nodes.length;
        if (e && e == 'move') {
            length = this.shapes.length;
            for (var i = 0; i < length; i++) {
                if (!this.shapes[i].selected) {
                    this.shapes[i].setMouseOut(); //调用每个对象的清除事件，用于修改将选中状态变成非选中状态的样式
                }
                if (this.shapes[i].tipInfo) {
                    this.shapes[i].tipHide();
                }
            }
            length = this.nodes.length;
            for (var i = 0; i < length; i++) {
                if (!this.nodes[i].selected) {
                    this.nodes[i].setMouseOut(); //调用每个对象的清除事件，用于修改将选中状态变成非选中状态的样式
                }
                if (this.nodes[i].tipInfo) {
                    this.nodes[i].tipHide();
                }
            }
        }
        else {
            for (var i = 0; i < length; i++) {
                this.nodes[i].cannelSelected(); //调用每个对象的清除事件，用于修改将选中状态变成非选中状态的样式
                if (this.nodes[i].tipInfo) {
                    this.nodes[i].tipHide();
                }
            }
            length = this.shapes.length;
            for (var i = 0; i < length; i++) {
                this.shapes[i].cannelSelected(); //调用每个对象的清除事件，用于修改将选中状态变成非选中状态的样式
                if (this.shapes[i].tipInfo) {
                    this.shapes[i].tipHide();
                }
            }
            MenuAction.getContextMenu(true);
        }
        this.selectedObj = []; //将所有选择对象清空
    };
    //设置机房背景图片
    this.setBackgroundImage = function(src) {
        this.backgroundimage = src;
    };
    //创建右键菜单
    this.createContextMenu = function() {
        if (!this.contextMenuOperation) {
            this.getOperation(); //先获取该设备的菜单操作对象组
        }
        this.destroyContextMenu(); //先销毁
        if (this.contextMenuOperation) {
            var menu = new Menu();
            menu.init('contextmenu', this);
            this.contextMenu = menu;
        }
    };
    //显示右键菜单
    this.showContextMenu = function() {
        if (this.contextMenu) {
            this.contextMenu.setContextMenuPosition(window.event.clientX, window.event.clientY);
            this.contextMenu.menuShow();
        }
    };
    //销毁右键菜单
    this.destroyContextMenu = function() {
        if (this.contextMenu) {//如果节点的右键菜单不为空
            this.contextMenu.destroyContextMenu();
            this.contextMenu = null;
        }
    };
    //获取节点操作权限
    this.getOperation = function() {
        this.contextMenuOperation = getXMLPropertyNode(xmlPath, 'operations', 'equipments', 'group'); //该对象针对每一个节点单独初始化，初始化后不清除
    };
    //初始化机房信息
    this.setRoominfo = function(o) {
        this.room = {
            id: o.ROOMID,
            name: o.ROOMNAME,
            // url: o.ROOMIMAGE,
            lat: o.LAT,
            lnt: o.LNT,
            type: o.ROOMTYPE
        };
        this.text = o.ROOMNAME;
    };
    //机房基本性能信息字段
    this.setReader = function() {
        this.reader = new Ext.data.JsonReader({
            root: 'data'
        }, [{ name: 'TEMPERATURE', type: 'string' },
            { name: 'HUMIDITY', type: 'string' },
            { name: 'SOOT', type: 'string' },
            { name: 'INUNDATE', type: 'string' },
            { name: 'AVOLTAGE', type: 'string' },
            { name: 'BVOLTAGE', type: 'string' },
            { name: 'CVOLTAGE', type: 'string' },
            { name: 'AELECTRICCURRENT', type: 'string' },
            { name: 'BELECTRICCURRENT', type: 'string' },
            { name: 'CELECTRICCURRENT', type: 'string'
}]);
    };
    //机房基本性能信息字段
    this.setItems = function() {
        this.items = [
			{ name: 'TEMPERATURE', fieldLabel: "温度(℃)" },
			{ name: 'HUMIDITY', fieldLabel: "湿度(%)" },
			{ name: 'SOOT', fieldLabel: "烟感" },
			{ name: 'INUNDATE', fieldLabel: "水浸" },
			{ name: 'AVOLTAGE', fieldLabel: "A相电压(V)" },
			{ name: 'BVOLTAGE', fieldLabel: "B相电压(V)" },
			{ name: 'CVOLTAGE', fieldLabel: "C相电压(V)" },
			{ name: 'AELECTRICCURRENT', fieldLabel: "A相电流(A)" },
			{ name: 'BELECTRICCURRENT', fieldLabel: "B相电流(A)" },
			{ name: 'CELECTRICCURRENT', fieldLabel: "C相电流(A)" }
		    ];
    };
}

/*
*   节点对象
*/
function Node() {
    this.id = ''; //对象ID
    this.text = ''; //对象文本
    this.left = 0; //对象距左边距离
    this.tipInfo = null; //对象的提示框
    this.top = 0; //对象的距顶距离
    this.status = '0'; //设备状态,默认为正常,主要用于修改对象对应的图片
    this.type = ''; //对象的设备属性
    this.isReal = true; //是否实时显示，默认为是
    this.isEdited = false; //该对象是否编辑过
    this.isSelected = false; //是否选中
    this.img = {
        src: '',
        width: '',
        height: '',
        path: '',
        ewidth: '',
        eheight: ''
    }; //对象的图片对象 src 图片名称 width 图片原宽度 height 图片原高度 path 图片文件路径 ewidth 图片编辑过宽度 eheight 图片编辑过的高度
    this.obj = null; //对象本身
    this.property = null; //设备属性对象
    this.performance = null; //设备性能对象
    //this.room = null; //设备对应的房间信息对象
    this.subNodes = null; //设备对应的下级节点
    this.superNodes = null; //设备对应的上级节点对象
    this.lineOut = null; //从节点出去的线
    this.lineIn = null; //进入节点的线
    this.contextMenu = null; //鼠标右键菜单
    this.items = null; //用于显示属性或性能的字段
    this.reader = null; //用于加载属性或性能的字段
    this.contextMenuOperation = null; //鼠标右键菜单操作对象数组
    this.alarm = {
        isalarm: false,
        alarmlevel: '',
        alarminfo: ''
    }; //告警基本信息
    //初始化节点对象
    this.init = function() {
        var group = _('group');
        var obj = null;
        if (this.type == '10010001') {
            createObj(obj = document.createElement('v:image'), { id: this.id, src: '../Images/room/nodeimage/' + this.img.src });
        }
        else {
            createObj(obj = document.createElement('v:image'), { id: this.id, src: '../Images/room/nodeimage/' + AllObjects.room.ROOMID + '_' + this.img.src });
        }
        obj.style.width = this.img.ewidth;
        obj.style.height = this.img.eheight;
        obj.style.top = this.top;
        obj.style.left = this.left;
        obj.style.position = 'absolute'; //将图片设置到上层
        obj.oncontextmenu = GroupEvent.onContextMenu;
        obj.attachEvent('ondblclick', GroupEvent.dblClick, false);
        //obj.onmousedown = GroupEvent.stopEvent;
        this.obj = obj;
        group.appendChild(obj);
        var ggd = group.getAttribute('container');
        ggd.nodes[ggd.nodes.length] = this;
    };
    //初始化节点数据
    this.initData = function(o) {
        this.id = 'node_' + o.LOGICEQUIPMENTID;
        this.text = o.LOGICEQUIPMENTNAME;
        this.left = o.LEFT;
        this.top = o.TOP;
        this.status = '0';
        this.type = o.EQUIPTYPE;
        this.isReal = o.ISMONITORPERF;
        this.img = eval('({' + o.EQUIPMENTPROPERTY + '})');
        //this.room = o.room;
        this.subNodes = '';
        this.superNodes = '';
        this.lineIn = '';
        this.lineOut = '';
        this.setProperty(o);
        this.setPerformance(o);
        this.tip({ tg: this.id, title: this.text, html: this.text });
    };
    //判断坐标是否在节点上
    this.pointInObj = function(x, y) {
        var res = false;
        x = GroupEvent.getX(x); //获取坐标点的真实位置
        y = GroupEvent.getY(y); //获取坐标点的真实位置
        var x1 = parseInt(this.obj.offsetLeft); //当前对象的左边距
        var x2 = x1 + parseInt(this.img.ewidth); //当前对象的左边距加对象本身的宽度
        var y1 = parseInt(this.obj.offsetTop); //对象的上边距
        var y2 = y1 + parseInt(this.img.eheight); //当前对象的上边距加对象本身的高度
        if ((x >= x1) && (x <= x2) && (y >= y1) && (y <= y2)) {
            res = true;
        }
        return res;
    };
    //设置选中状态
    this.setSelected = function() {
        this.isSelected = true; //将状态设置为选中
        this.obj.style.border = "2px solid Green"; //设置选中时候的样式
    };
    //清除选中状态
    this.cannelSelected = function() {
        this.isSelected = false;
        this.obj.style.border = '';
        this.destroyContextMenu();
    };
    //设置鼠标移动状态
    this.setMouseMove = function() {
        this.obj.style.border = "2px solid Green"; //设置选中时候的样式
    };
    //设置鼠标移出状态
    this.setMouseOut = function() {
        this.obj.style.border = '';
    };
    /*
    *   设置告警样式
    *   @param  level   告警等级
    */
    this.setAlarm = function() {
        var am = arguments[0];
        this.alarm = {
            isalarm: true,
            alarmlevel: am.ALARMLEVEL,
            alarminfo: am
        };
        var src = this.obj.src;
        var startIndex = src.indexOf('.');
        switch (this.alarm.alarmlevel) {
            case 0:
                this.obj.src = src.substring(startIndex) + level + src.substring(startIndex + 1);
                break;
            default:
                this.obj.src = src.substring(startIndex) + level + src.substring(startIndex + 1);
                break;
        }
    };
    /*创建对象的提示信息*/
    this.tip = function(t) {
        var ttp = t || { tg: 'group', title: '节点对象', html: '基本文本' };
        this.tipInfo = new Ext.ToolTip({
            target: ttp.tg,
            title: ttp.title,
            //width: 200,
            html: ttp.html,
            trackMouse: true,
            dismissDelay: 15000
        });
    };
    /*显示提示框*/
    this.tipShow = function() {
        //        if (!this.tipInfo) {
        //            this.tip({ tg: this.id, title: getResourceName(this.type), html: this.text });
        //        }
        //        this.tipInfo.showAt([parseInt(this.left) + 20, parseInt(this.top) - 30]);
        var length = 0;
        if (!this.tipInfo) {//如果还没有获取提示信息
            var d = getServerData("Handler.ashx?tablename=&resourcetypeid=" + this.property.equiptype + "&where=" + this.property.id + "&type=&sort=");
            var data = eval('(' + d + ')');
            if (data.data.length > 0) {
                var strHTML = "";
                var rows = Topo_RoomPlaneRight.GetEquipProperty("", this.property.equiptype, "", "to_number(SERIAL)", "  isvisible='Y'").value;
                if (rows && rows.Rows.length > 0) {
                    length = rows.Rows.length;
                    for (var i = 0; i < length; i++) {
                        strHTML += rows.Rows[i]["CHFIELD"] + ":" + data.data[0][rows.Rows[i]["ENFIELD"]] + "<br />";
                    }
                    this.tipInfo = new Ext.ToolTip({ target: this.id,
                        html: strHTML,
                        trackMouse: true,
                        title: this.property.logicequipname,
                        dismissDelay: 15000
                    });
                }
            }
        }
        var t = this.tipInfo;
        if (t) {
            if (length > 5) {
                t.showAt([parseInt(this.left) + 20, this.top - 100]);
            }
            else {
                t.showAt([parseInt(this.left) + 40, parseInt(this.top) + 40]);
            }
        }
    };
    /*隐藏提示框*/
    this.tipHide = function() {
        if (this.tipInfo) {
            this.tipInfo.hide();
        }
    };
    //创建右键菜单
    this.createContextMenu = function() {
        if (!this.contextMenuOperation) {
            this.getOperation(); //先获取该设备的菜单操作对象组
        }
        if (this.contextMenuOperation) {
            var menu = new Menu();
            menu.init('contextmenu', this);
            this.contextMenu = menu;
        }
    };
    //显示右键菜单
    this.showContextMenu = function() {
        if (this.contextMenu) {
            this.contextMenu.setContextMenuPosition(window.event.clientX, window.event.clientY);
            this.contextMenu.menuShow();
        }
    };
    //销毁右键菜单
    this.destroyContextMenu = function() {
        if (this.contextMenu) {//如果节点的右键菜单不为空
            this.contextMenu.destroyContextMenu();
            this.contextMenu = null;
        }
    };
    //获取节点操作权限
    this.getOperation = function() {
        this.contextMenuOperation = getXMLPropertyNode(xmlPath, 'operations', 'equipments', this.type); //该对象针对每一个节点单独初始化，初始化后不清除
    };
    //级联删除
    this.remove = function() {
        if (this.subNodes) {
            if (confirm('该节点下面存在子节点，确认都一起删除吗？')) {
                //目前只是做了理论上的删除,并没有真正的就节点从界面上删除,有待修改
                this.isEdited = true; //表明该节点已经编辑过
                var length = this.subNodes.length;
                for (var i = 0; i < length; i++) {
                    if (this.subNodes[i].subNodes) {//如果子节点也有子节点
                        this.subNodes[i].remove(); //就将子节点删除
                    }
                    else {
                        //this.subNodes [i];//直接删除该节点
                        //从界面中删除节点
                    }
                }
                //this.superNodes;//上级节点删除该节点
                //从界面中删除节点
            }
        }
        else if (this.superNodes) { //该节点已经是最下面已经一级节点
            //this.superNodes;//上级节点删除该节点
            //从界面中删除节点
        }
        else {  //如果节点孤立,既没有上级节点也没有下级节点
            //直接从界面中删除
            var group = _('group');
            var ggd = group.getAttribute('container');
            group.removeChild(this.obj);
            ggd.count--;
        }
    };
    //设置属性对象
    this.setProperty = function(o) {
        this.property = {
            id: o.EQUIPMENTID,
            equiptype: o.EQUIPTYPE,
            logicequipid: o.LOGICEQUIPMENTID,
            logicequipname: o.LOGICEQUIPMENTNAME,
            uplogicequipid: o.UPLOGICEQUMENTID
        };
    };
    //设置性能对象
    this.setPerformance = function(o) {
        this.performance = {
            id: o.EQUIPMENTID,
            url: ''
        };
    };
}

/*
*   创建多边形
*   多边形有自动闭合功能
*/
function Shape() {
    this.id = 'shape_'; //ID
    this.number = 0; //计数器
    this.obj = null; //保存对象本身
    this.isInit = false; //是否已经初始化
    this.selected = false; //该设备是否选中
    this.tipInfo = null; //对象提示框
    this.x = 0;
    this.y = 0;
    this.left = 0;
    this.top = 0;
    this.filled = true; //是否填充
    this.path = 'm0,0 l0,0'; //多边形路径
    this.strokecolor = 'green'; //画多边形时的线颜色
    this.strokeweight = '1'; //画多边形时的线宽度
    this.coordsize = '100,100'; //比例
    this.fillcolor = 'green'; //多边形填充颜色,只有在filled=true的情况下有效
    this.property = null; //设备基本物理属性
    this.type = '';
    //  this.alarm = false; //标记是否有告警，默认为没有
    this.position = 'absolute';
    this.contextMenu = null; //鼠标右键菜单
    this.contextMenuOperation = null; //鼠标右键菜单操作对象数组
    this.text = '';
    this.alarm = {
        isalarm: false,
        alarmlevel: '',
        alarminfo: ''
    }; //告警信息描述
    this.init = function() {
        this.obj = group.appendChild(document.createElement("<v:shape path='m0,0 l0,0' filled='true' style='POSITION:absolute;z-index:1;left:" + this.x + ";top:" + this.y + ";cursor:pointer;width:100;height:100;filter: Alpha(Opacity=60);' strokecolor='black' strokeweight='1' coordsize='100,100' fillcolor='yellow'/>"));
        this.obj.id = this.id;
        this.obj.path = this.path;
        this.obj.strokecolor = this.strokecolor;
        this.obj.strokeweight = this.strokeweight;
        this.obj.coordsize = this.coordsize;
        this.obj.fillcolor = this.fillcolor;
        this.obj.filled = this.filled;
        this.obj.style.left = this.left;
        this.obj.style.top = this.top;
        this.obj.style.position = this.position;
        this.obj.oncontextmenu = GroupEvent.onContextMenu;
        // this.obj.ondblclick = GroupEvent.dblClick; //双击事件
        this.obj.attachEvent('ondblclick', GroupEvent.dblClick, false);
        var ggd = group.getAttribute('container');
        ggd.shapes[ggd.shapes.length] = this;
    };
    //初始化基本参数
    this.initData = function(o) {
        this.strokecolor = 'green';
        this.filled = 'f';
        this.x = o.LEFT;
        this.y = o.TOP;
        this.left = o.LEFT;
        this.top = o.TOP;
        this.path = eval('({' + o.EQUIPMENTPROPERTY + '})').path;
        this.property = {
            id: o.EQUIPMENTID,
            equiptype: o.EQUIPTYPE,
            logicequipid: o.LOGICEQUIPMENTID,
            logicequipname: o.LOGICEQUIPMENTNAME,
            uplogicequipid: o.UPLOGICEQUMENTID
        };
        this.id = this.id + this.property.logicequipid;
        this.type = this.property.equiptype;
        this.text = this.property.logicequipname;
    };
    //设置鼠标移动状态
    this.setMouseMove = function() {
        this.strokecolor = 'blue';
        this.obj.strokecolor = this.strokecolor;
        this.filled = 't';
        this.obj.filled = this.filled;
        if (!this.alarm.isalarm) {
            this.fillcolor = 'green';
        }
        this.obj.fillcolor = this.fillcolor;
    };
    //设置鼠标移出状态
    this.setMouseOut = function() {
        if (!this.alarm.isalarm) {//如果没有告警就恢复
            this.strokecolor = 'green';
            this.obj.strokecolor = this.strokecolor;
            this.filled = 'f';
            this.obj.filled = this.filled;
            this.fillcolor = '';
            this.obj.fillcolor = this.fillcolor;
        }
        if (this.alarm.isalarm) {
            this.setAlarmStatus(this.alarm.alarmlevel);
        }
    };
    //设置选中状态
    this.setSelected = function() {
        this.setMouseMove();
        this.selected = true;
    };
    //设置取消状态
    this.cannelSelected = function() {
        this.setMouseOut();
        this.selected = false;
    };
    /*创建对象的提示信息*/
    this.tip = function(t) {
        var ttp = t || { tg: 'group', title: '节点对象', html: '基本文本' };
        this.tipInfo = new Ext.ToolTip({
            target: ttp.tg,
            title: ttp.title,
            //width: 200,
            html: ttp.html,
            trackMouse: true,
            dismissDelay: 15000
        });
    };
    /*显示提示框*/
    this.tipShow = function() {
        //        if (!this.tipInfo) {
        //            this.tip({ tg: this.id, title: getResourceName(this.property.equiptype), html: this.text });
        //        }
        //        this.tipInfo.showAt([parseInt(this.x) + 20, this.y]);
        var length = 0;
        if (!this.tipInfo) {//如果还没有获取提示信息
            var d = getServerData("Handler.ashx?tablename=&resourcetypeid=" + this.property.equiptype + "&where=" + this.property.id + "&type=&sort=");
            var data = eval('(' + d + ')');
            if (data.data.length > 0) {
                var strHTML = "";
                var rows = Topo_RoomPlaneRight.GetEquipProperty("", this.property.equiptype, "", "to_number(SERIAL)", "  isvisible='Y'").value;
                if (rows && rows.Rows.length > 0) {
                    length = rows.Rows.length;
                    for (var i = 0; i < length; i++) {
                        strHTML += rows.Rows[i]["CHFIELD"] + ":" + data.data[0][rows.Rows[i]["ENFIELD"]] + "<br />";
                    }
                    this.tipInfo = new Ext.ToolTip({ target: this.obj.id,
                        html: strHTML,
                        trackMouse: true,
                        title: this.property.logicequipname,
                        dismissDelay: 15000
                    });
                    // con.istip = true;
                }
            }
        }
        var t = this.tipInfo;
        if (t) {
            if (length > 5) {
                t.showAt([parseInt(this.x) + 40, parseInt(this.y) - 100]);
            }
            else {
                t.showAt([parseInt(this.x) + 40, parseInt(this.y) + 40]);
            }
        }
    };
    /*隐藏提示框*/
    this.tipHide = function() {
        if (this.tipInfo) {
            this.tipInfo.hide();
        }
    };
    /*
    *   设置告警样式
    *   @param  level   告警等级
    */
    this.setAlarm = function() {
        var am = arguments[0];
        var al = MenuAction.getAlaramLevel(this.alarm.alarmlevel); //保存之前的告警等级
        this.alarm = {
            isalarm: true,
            alarmlevel: am.ALARMLEVEL,
            alarminfo: am
        };
        var aln = MenuAction.getAlaramLevel(this.alarm.alarmlevel); //获取新的告警等级
        //        if (this.alarm.alarmlevel.length > 0) {
        //            this.setAlarmStatus(this.alarm.alarmlevel);
        //        }
        //有更高等级的告警出现
        if (al < aln) {
            this.setAlarmStatus(this.alarm.alarmlevel);
        }
    };
    this.setAlarmStatus = function() {
        var alarmColor = MenuAction.getAlaramLevelColor(arguments[0]); //根据告警等级获取告警颜色
        this.strokecolor = alarmColor;
        this.obj.strokecolor = this.strokecolor;
        this.filled = 't';
        this.obj.filled = this.filled;
        this.fillcolor = alarmColor;
        this.obj.fillcolor = this.fillcolor;
    };
    /*清除告警状态*/
    this.clearAlarm = function() {
        this.alarm = { isalarm: false, alarmlevel: '', alarminfo: '' };
        this.cannelSelected();
    };
    //判断坐标是否在节点上
    this.pointInObj = function(x, y) {
        var res = false;
        x = GroupEvent.getX(x); //获取坐标点的真实位置
        y = GroupEvent.getY(y); //获取坐标点的真实位置
        var point = { x: x, y: y };
        var pl = this.path.substring(this.path.indexOf('l') + 1).split(',');
        var ploy = [];
        var length = pl.length;
        var l = parseInt(this.left);
        var t = parseInt(this.top);
        for (var i = 0; i < length; i = i + 2) {
            ploy.push({ x: l + parseInt(pl[i]), y: t + parseInt(pl[i + 1]) });
        }
        return this.checkPP(point, ploy);
        //return this.isInsidePolygon(point, ploy);
    };
    this.crossMul = function(v1, v2) {
        return v1.x * v2.y - v1.y * v2.x;
    };
    this.checkCross = function(p1, p2, p3, p4) {
        var v1 = { x: p1.x - p3.x, y: p1.y - p3.y };
        var v2 = { x: p2.x - p3.x, y: p2.y - p3.y };
        var v3 = { x: p4.x - p3.x, y: p4.y - p3.y };
        var v = this.crossMul(v1, v3) * this.crossMul(v2, v3);
        v1 = { x: p3.x - p1.x, y: p3.y - p1.y };
        v2 = { x: p4.x - p1.x, y: p4.y - p1.y };
        v3 = { x: p2.x - p1.x, y: p2.y - p1.y };
        return (v <= 0 && this.crossMul(v1, v3) * this.crossMul(v2, v3) <= 0) ? true : false;
    };
    this.checkPP = function(point, polygon) {
        var p1, p2, p3, p4;
        p1 = point;
        p2 = { x: -100, y: point.y };
        var count = 0;
        //对每条边都和射线做对比
        for (var i = 0; i < polygon.length - 1; i++) {
            p3 = polygon[i];
            p4 = polygon[i + 1];
            if (this.checkCross(p1, p2, p3, p4) == true) {
                count++;
            }
        }
        p3 = polygon[polygon.length - 1];
        p4 = polygon[0];
        if (this.checkCross(p1, p2, p3, p4) == true) {
            count++
        }
        return (count % 2 == 0) ? false : true;
    };
    this.isInsidePolygon = function(point, poly) {
        // 判断点象限函数
        var getQuad = function(pt) {
            var qid = (pt.x >= 0) ? ((pt.y >= 0) ? 0 : 3) : ((pt.y >= 0) ? 1 : 2);
            return qid;
        };
        // 检查顶点数
        if (poly.length < 3)
            return false;
        // 平移多边形，使point在新坐标系中为原点
        var vtxs = [];
        for (var pi in poly)
            vtxs[pi] = { x: (poly[pi].x - point.x), y: (poly[pi].y - point.y) };
        var sum = 0; //弧长和*2/π
        var q1, q2; //相邻两节点的象限
        var ep = 0; //用来存放外积
        var dq = false; //用来存放两点是否在相对象限中
        q1 = getQuad(vtxs[0]);
        var length = vtxs.length;
        for (var vi = 1; vi < length; vi++) {
            // point为多边形的一个节点
            if (vtxs[vi].x == 0 && vtxs[vi].y == 0)
                return true;
            // 计算两点向量外积，用来判断点是否在多边形边上（即三点共线）
            ep = vtxs[vi].y * vtxs[vi - 1].x - vtxs[vi].x * vtxs[vi - 1].y;
            dq = (vtxs[vi - 1].x * vtxs[vi].x <= 0) && (vtxs[vi - 1].y * vtxs[vi].y <= 0);
            if ((ep == 0) && dq)
                return true;
            // 计算象限判断相邻两点的象限关系，并修改sum
            q2 = getQuad(vtxs[vi]);
            if (q2 == (q1 + 1) % 4) {
                sum = sum + 1;
            } else if (q2 == (q1 + 3) % 4) {
                sum = sum - 1;
            } else if (q2 == (q1 + 2) % 4) {
                if (ep > 0) {
                    sum = sum + 2;
                } else {
                    sum = sum - 2;
                }
            }
            q1 = q2;
        }
        //alert(sum);
        if (sum > 0)
            return true;
        return false;
    };
    //创建右键菜单
    this.createContextMenu = function() {
        if (!this.contextMenuOperation) {
            this.getOperation(); //先获取该设备的菜单操作对象组
        }
        if (this.contextMenuOperation) {
            var menu = new Menu();
            menu.init('contextmenu', this);
            this.contextMenu = menu;
        }
    };
    //显示右键菜单
    this.showContextMenu = function() {
        if (this.contextMenu) {
            this.contextMenu.setContextMenuPosition(window.event.clientX, window.event.clientY);
            this.contextMenu.menuShow();
        }
    };
    //销毁右键菜单
    this.destroyContextMenu = function() {
        if (this.contextMenu) {//如果节点的右键菜单不为空
            this.contextMenu.destroyContextMenu();
            this.contextMenu = null;
        }
    };
    //获取节点操作权限
    this.getOperation = function() {
        this.contextMenuOperation = getXMLPropertyNode(xmlPath, 'operations', 'equipments', this.property.equiptype); //该对象针对每一个节点单独初始化，初始化后不清除
    };
    this.mouseDown = function(x, y) {
        if (!this.isInit) {
            this.x = GroupEvent.getPositionX();
            this.y = GroupEvent.getPositionY();
            this.left = x;
            this.top = y;
            this.obj.style.left = this.left;
            this.obj.style.top = this.top;
            this.isInit = true;
            this.obj.path.value = this.path;
        }
        this.path = this.obj.path.value.replace("e", "");
    };
    this.mouseMove = function(x, y) {
        this.obj.path.value = this.path + "," + (GroupEvent.getPositionX() - this.x) + "," + (GroupEvent.getPositionY() - this.y);
        this.obj.path.value = this.obj.path.value.replace(",0,0,", ",0,").replace(",0 e", "e");
        this.position += '&' + GroupEvent.getPositionX() + ',' + GroupEvent.getPositionY();
    };
    this.mouseUp = function() {
        if (event.button == 2) {
            this.obj.path.value = this.path.value + "x e";
        }
        alert(GroupEvent.getPositionX() + ',' + GroupEvent.getPositionY());
    };
}

/*
*   整个的工具条 菜单对象
*/
function Menu() {
    this.id = 'menu'; //菜单ID
    this.menutype = 'toolbar'; //菜单类型 toolbar 工具条 contextmenu 右键
    this.equipid = ''; //节点对应的设备ID
    this.equiptype = null; //节点对应的设备类型
    this.obj = null; //菜单对象自身
    this.left = 10; //菜单左边距
    this.top = 3; //菜单上边距
    this.height = 0; //菜单高度
    this.width = 0; //菜单宽度
    this.imgPath = '../Images/Topo/operate/'; //图片的基本路径
    this.display = false; //菜单默认不显示
    //初始化类
    this.init = function(menutype, o) {
        var group = _('group');
        if (o.property) {
            this.equiptype = o.property.equiptype;
        }
        switch (menutype.toLowerCase()) {
            case 'contextmenu':
                this.obj = this.contextMenu(o);
                group.appendChild(this.obj);
                break;
            case 'toolbar':
                this.obj = this.toolMenu();
                group.appendChild(this.obj);
                break;
        }
    };
    //创建右键菜单
    this.contextMenu = function(o) {
        if (o && o.contextMenuOperation) {//如果创建右键菜单对象不为空
            var menuContainer = document.createElement('div'); //创建右键菜单的基本容器
            menuContainer.id = "MenuContainer";
            var menuShadow = document.createElement('div'); //创建右键菜单的阴影DIV
            menuShadow.id = "MenuContainerShadow";
            var menuContainerContent = document.createElement('div'); //创建右键菜单内容DIV
            menuContainerContent.id = "MenuContainerContent";
            menuContainer.appendChild(menuShadow); //将阴影DIV添加到菜单
            menuContainer.appendChild(menuContainerContent); //将内容DIV添加到菜单
            var menu = null; //菜单项
            var em = null; //菜单内容
            var length = o.contextMenuOperation.length;
            for (var i = 0; i < length; i++) {
                menu = document.createElement('div');
                menu.id = 'Menu_' + o.contextMenuOperation[i].operationdid;
                menu.activetab = i; //创建菜单顺序
                menu.onmousedown = GroupEvent.stopEvent; //阻止事件的冒泡行为
                if (o.contextMenuOperation[i].isdisplay) { //如果操作可用，添加相应的事件
                    menu.className = 'Menu';
                    MenuAction.attachevent(menu, 'click', eval(o.contextMenuOperation[i].action), o);
                }
                else {
                    menu.className = 'Menu_UnEnable';
                }
                menu.style.backgroundImage = "url('" + this.imgPath + o.contextMenuOperation[i].ico + "')"; //添加菜单左边图标
                em = document.createElement('em');
                em.innerHTML = o.contextMenuOperation[i].name; //菜单文字
                menu.appendChild(em);
                menuContainerContent.appendChild(menu);
            }
            /*  说明：
            *       理论上直接等于菜单内容框的高度就可以，但此时菜单内容框由于css没有加载，还没有高度，只能直接运算
            *       该处的高度计算为 (菜单项数目 * 每一菜单项高度 - 偏移量)
            *       具体值可以在common/ContextMenu.css中查找"菜单阴影框"和"每一个具体菜单项"说明
            *       qfkong      2010.3.24 17:00
            */
            menuShadow.style.height = (length * 26 - 2) + 'px';
        }
        return menuContainer;
    };
    /*
    *   对象绑定事件
    *   @param  target  对象
    *   @param  eventName   事件对象
    *   @param  handler 事件
    *   @param  argsObject  参数对象
    */
    this.attachevent = function(target, eventName, handler, argsObject) {
        var eventHandler = handler;
        if (argsObject) {
            eventHander = function(e) {
                handler.call(e, argsObject);
            }
        }
        if (window.attachEvent)//IE
            target.attachEvent("on" + eventName, eventHander, false);
        else//FF
            target.addEventListener(eventName, eventHander, false);
    };
    //创建工具条
    this.toolMenu = function() {

    };
    //菜单对象菜单项的移动样式修改
    this.mousemove = function(o) {
        if (o.className != "Menu_UnEnable") {
            if (o.className == 'Menu_Selected') {
                o.className = 'Menu';
            }
            else {
                o.className = 'Menu_Selected';
            }
        }
    };
    //显示菜单
    this.menuShow = function() {
        this.obj.style.display = 'block';
    };
    //隐藏菜单
    this.menuHidden = function() {
        this.obj.style.display = 'none';
    };
    //销毁菜单
    this.destroyContextMenu = function() {
        this.menuHidden();
        var o = _('MenuContainer');
        o.parentNode.removeChild(o); //将菜单对象移除
    };
    //设置右键菜单显示和位置
    this.setContextMenuPosition = function(x, y) {
        var contextMenu = _('MenuContainer');
        var group = _('group');
        var g_x = GroupEvent.getXPosition(group); //group的左边距
        var g_y = GroupEvent.getYPosition(group); //group的上边距
        var g_x_x = g_x + parseInt(group.offsetWidth); //左边距加上group的宽度
        var g_y_y = g_y + parseInt(group.offsetHeight); //上边距加上group的高度
        var w = 140; //右键菜单的宽度
        var h = parseInt(_('MenuContainerShadow').offsetHeight); //右键菜单的高度
        var l = x + 10; //菜单要呈现的位置左边距
        var t = y + 10; //菜单要呈现的位置的上边距
        if (x + w > g_x_x) {
            l = x - w;
        }
        if (y + h > g_y_y) {
            t = y - h;
        }
        contextMenu.style.left = l;
        contextMenu.style.top = t;
        // alert(l + ',' + t);
    };
}

/*
*   属性 性能窗口 使用EXTJS操作
*   将属性性能一次性弹出，分成不同的页签显示，根据菜单选择而显示不同的页签
*/

function Window() {
    this.id = 'propertyWindow'; //默认窗口ID
    this.left = 100; //窗口左边距
    this.top = 3;  //窗口上边距
    this.height = 370;  //窗口高度
    this.width = 450;   //窗口宽度
    this.title = '';  //窗口标题
    this.activeTab = 0; //窗口加载激活页签,默认为0
    this.isSelected = false; //窗口是否选中，默认为不选中
    this.obj = null;  //窗口对象
    this.items = null;  //窗口的页签对象
    this.tablename = ""; //属性窗口表名
    this.cols = ""; //查询用的字段字符串
    //窗口初始化
    this.init = function(o, menu) {
        if (!!menu) {
            this.getActiveTab(menu);
        }
        if (!!o) {
            if (!o.type) {
                this.setTitle(o.room.name); //初始化窗口标题
            }
            else {
                this.setTitle(o.text); //初始化窗口标题
            }
        }
        else {
            this.setItems();
        }
        this.setPosition();
        this.obj = new Ext.Window({
            width: this.width,
            height: this.height,
            x: this.left,
            y: this.top,
            items: new Ext.TabPanel({
                id: 'mainTabPanel',
                activeTab: this.activeTab,
                border: false,
                layoutOnTabChange: true,
                defaults: { autoScroll: true, height: 400 },
                enableTabScroll: true,
                closeAll: true,
                tabWidth: 250,
                minTabWidth: 120
            }),
            plain: true, //true则主体背景透明，false则主体有小差别的背景色，默认为false
            title: this.title
        });
        this.setItems(o);
    };
    this.setItems = function(o) {
        /*
        *   说明：该处创建各设备属性和性能窗口，属性都使用相同的页面，从节点的属性对象中传递参数即可
        *         而性能，部分是使用页面传递参数，部分需要临时生成
        *         如果节点对象为空，就直接显示，这种状态不存在
        */
        // if (!!o && o.performance) {
        if (!!o && o.property) {
            this.activeTab = 0;
            var tablename = getResourceTableName(o.property.equiptype);
            var sw = o.property.id;
            //            if (tablename.length == 0) {
            //               
            //                //                tablename = 'TB_STATION';
            //                //                sw = 'where ne_id=\'' + o.property.id + '\'';
            //            }
            this.addPanel('mainTabPanel', 'equip_' + o.property.id, '属性', false, tablename, o.type, sw, 'PROPERTY', '');
            //  this.addPanel('mainTabPanel', 'equip_' + o.property.id, '属性', false, 'TB_STATION', o.type, 'where equip_id=\'' + o.property.id + '\'', 'PROPERTY', '');
            //this.addPanel('mainTabPanel', 'panel_1', '添加测试卡', false, 'Metarnet', '', 'PROPERTY');
            //Ext.getCmp('mainTabPanel').remove(Ext.getCmp('panel_1').id);
           //Ext.getCmp('mainTabPanel').remove(Ext.getCmp('panel_1').id);
        }
        else {
            this.addPanel('mainTabPanel', 'env_' + o.room.id, '动力环境数据', false, 'ENV_YXYC_TMP', '10020015', 'where roomid=\'' + o.room.id + '\'', 'PROPERTY', '');
            this.addPanel('mainTabPanel', 'room_' + o.room.id, '机房属性', false, 'ROOM_LIST', '10020004', 'where roomid=\'' + o.room.id + '\'', 'PROPERTY', '');
        }
    };
    //添加面板
    this.addPanel = function(oID, nID, title, isClose, tableName, typeid, sw, type, sort) {
        var originalPanel = Ext.getCmp(oID);
        var newTab = Ext.getCmp(nID);
        if (originalPanel) {
            if (newTab) {
                originalPanel.remove(newTab.id); // 如果该选项卡面板里已有选项卡，先将其移除
            }
            var tp = new Ext.Panel({
                iconCls: 'tab',
                id: nID,
                enableTabScroll: true,
                defaults: { autoScroll: true, height: 310, width: 440 },
                xtype: 'tabpanel',
                closable: isClose,
                title: title,
                listeners: {
                    activate: function(tab) {
                        var fPanel = Ext.getCmp('fp_' + nID);
                        if (!fPanel) {
                            fPanel = MenuAction.createFormPanel(tableName, 'fp_' + nID);
                            tab.add(fPanel);
                            Ext.getCmp('mainTabPanel').activate(1);
                        }
                        Ext.getCmp('fp_' + nID).getForm().load({
                            url: 'Handler.ashx',
                            params: {
                                tablename: tableName,
                                resourcetypeid: typeid,
                                where: sw,
                                type: type,
                                sort: sort
                            },
                            success: function(form, action) {
                                //alert('数据加载成功!');
                            },
                            waitMsg: '正在载入数据...',
                            waitTitle: "请稍候"
                        });
                        // }
                    }
                }
            });
            originalPanel.add(tp).show(); // 向选项卡面板里添加选项卡
            originalPanel.setActiveTab(0);
        }
    };

    //创建设备性能窗口
    this.createHTML = function(o) {
        return new Ext.FormPanel({
            id: 'form',
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            defaults: { width: 230, border: false, readOnly: true }, //disabled: true, 不能输入
            defaultType: 'textfield', //默认的input类型
            width: this.width,
            height: this.height,
            reader: o.reader,
            items: o.items,
            labelSeparator: ':', //定义文字标签后的符号
            labelWidth: 160
        });
    };
    //为机房性能加载数据
    this.loadData = function(id, o, w, type) {
        var ob = null;
        switch (type) {
            case 'xn':
                ob = { roomid: o.room.id,
                    type: "roomenv"
                };
                break;
            case 'sx':
                ob = { type: "room",
                    tablename: this.tablename,
                    columns: this.cols,
                    where: w
                };
                break;
            default: break;
        }
        var f = Ext.getCmp(id);
        f.getForm().load({
            url: 'Handler.ashx',
            params: ob,
            //success: function(form, action) { f.disabled(); },
            waitMsg: '正在载入数据...',
            waitTitle: "请稍候"
        });
    };
    //获取激活页签
    this.getActiveTab = function(type) {
        switch (type.toLowerCase()) {
            case 'property':
                this.activeTab = 1;
                break;
            case 'performance':
                this.activeTab = 2;
                break;
            default:
                this.activeTab = 0;
                break;
        }
    };
    //设置窗口的位置
    this.setPosition = function() {
        var group = _('group');
        var g_x = GroupEvent.getXPosition(group);
        var g_y = GroupEvent.getXPosition(group);
        var g_x_x = group.offsetWidth;
        var g_y_y = group.offsetHeight;
        var x = 100; //(g_x_x - this.width) / 2 + g_x;
        var y = 20; //(g_y_y - this.height) / 2 + g_y;
        this.left = x;
        this.top = y;
    };
    //设置窗口标题
    this.setTitle = function(title) {
        this.title = title;
    };
    //将窗口显示
    this.show = function() {
        win.obj.show();
    };
    //将窗口隐藏
    this.hide = function() {
        win.obj.hide();
    };
    //将窗口销毁
    this.destroy = function() {
        win.obj.destroy();
    };
    this.createPro = function(typeid) {
        var columns = Topo_RoomPlaneRight.GetColumnsList(typeid).value;
        var itemsReader = [];
        var p_items = [];
        //    if (columns) {
        var length = columns.Rows.length;
        this.tablename = columns.Rows[0].QUERYFROMVIEW;
        for (var i = 0; i < length; i++) {
            p_items.push({
                name: columns.Rows[i].ENFIELD,
                fieldLabel: columns.Rows[i].CHFIELD
            });
            itemsReader.push({
                name: columns.Rows[i].ENFIELD,
                type: 'string'
            });
            this.cols += columns.Rows[i].ENFIELD;
            if (i < length - 1) {
                this.cols += "$";
            }
        }
        var jReader = new Ext.data.JsonReader({
            root: 'data'
        }, itemsReader);
        return new Ext.FormPanel({
            id: 'formp',
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            defaults: { width: 230, border: false, readOnly: true }, //disabled: true, 不能输入
            defaultType: 'textfield', //默认的input类型
            width: this.width,
            height: this.height,
            reader: jReader,
            items: p_items,
            labelSeparator: ':', //定义文字标签后的符号
            labelWidth: 100
        });
    };

    this.setItemsByPro = function(o) {
        this.p_items = o.items;
        this.reader = o.reader;
    }
}

/*
*   所有菜单操作事件集合
*/
var MenuAction = {
    open: function() {
        MenuAction.destroyContextMenu(); //先将右键菜单销毁
        MenuAction.showWindow();
    },
    getProperty: function() {
        MenuAction.createWindow('property');
    },
    getPerformance: function() {
        MenuAction.createWindow('performance');
    },
    getAlarm: function() {
        var am = arguments[0];
        var id = '';
        var type = '';
        switch (am.type.toLowerCase()) {
            case 'group':
                id = am.room.id;
                type = 'ROOM';
                break;
            case '10020001':
            case '10020002':
            case '10020018':
                id = am.property.id;
                type = am.property.equiptype;
                break;
            default:
                break;
        }
        MenuAction.destroyContextMenu(true);
        var group = _('group');
        var ggd = group.getAttribute('container');
        if (ggd.contextMenu) {
            ggd.destroyContextMenu();
        }
        OpenModalDialog('../AlarmManager/AlarmInfoShow.aspx?objid=' + id + '&type=' + type + '&text=', 800, 400);
    },
    getPanel: function() {
        var am = arguments[0];
        MenuAction.destroyContextMenu();
        //Ext.Msg.alert('提示', '设备面板');
        switch (am.property.equiptype) {
            case '10020001': //基站面板图
            case 'TBS':
                OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + am.property.equiptype + '&equipid=' + am.property.id, 600, 630);
                break;
            case '10020018': //LOOP4200面板图
            case 'LOOP4200':
                OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + am.property.equiptype + '&equipid=' + am.property.id, 1000, 400);
                break;
            case '10020017': //LOOP3440面板图
            case 'LOOP3440':
                OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + am.property.equiptype + '&equipid=' + am.property.id, 1000, 450);
                break;
            default:
                OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + am.property.equiptype + '&equipid=' + am.property.id, 600, 630);
                break;
        }
    },
    save: function() {
        MenuAction.destroyContextMenu(); //先将右键菜单销毁
    },
    remove: function() {
        MenuAction.destroyContextMenu(); //先将右键菜单销毁
    },
    //设置设备关联设备
    setRelevance: function() {
        MenuAction.destroyContextMenu(); //先将右键菜单销毁
    },
    quit: function() {
        MenuAction.destroyContextMenu();
    },
    openVideo: function() {
        var ggd = group.getAttribute('container');
        MenuAction.destroyContextMenu();
        var ds = Topo_RoomPlaneRight.getVideoInfoFromRoomid(ggd.room.id).value; //获取该机房内视频通道信息 

        if (ds.Tables[0] != null) {
            if (ds.Tables[0].Rows.length > 0) {
                if (ds.Tables[0].Rows.length > 1) {
                    //                    var videoDiv = document.createElement('div');
                    //                    videoDiv.id = 'divVideo';
                    var videoDiv = _('divVideo');
                    videoDiv.innerHTML = ''; //先清除视频菜单内容
                    var menuDIV, menuEM;
                    var length = ds.Tables[0].Rows.length;
                    for (var vi = 0; vi < length; vi++) {
                        menuDIV = document.createElement('div');
                        menuDIV.id = 'menu_' + vi;
                        // menuEM = document.createElement('em');
                        menuEM = "<em onclick=\"MenuAction.setVideo('" + ds.Tables[0].Rows[vi].IP + "','" + ds.Tables[0].Rows[vi].CHANNEL + "');MenuAction.setHidenVideo();\">";
                        //MenuAction.attachevent(menuDIV, 'click', eval('MenuAction.setVideo'), [ds.Tables[0].Rows[vi].IP, ds.Tables[0].Rows[vi].CHANNEL]);
                        menuEM += "通道:&nbsp;&nbsp;" + ds.Tables[0].Rows[vi].CHANNEL + "</em>";
                        menuDIV.innerHTML = menuEM;
                        videoDiv.appendChild(menuDIV);
                    }
                    videoDiv.style.display = 'block';
                    videoDiv.style.left = event.clientX - 20;
                    videoDiv.style.top = event.clientY + 30;
                }
                else {
                    MenuAction.setVideo(ds.Tables[0].Rows[0].IP, ds.Tables[0].Rows[0].CHANNEL);
                }
            }
        }
    },
    setHidenVideo: function() {
        _('divVideo').style.display = 'none';
    },
    setVideo: function(vip, vchannel) {
        var am = arguments[0];
        if (arguments.length == 1) {
            vip = am[0];
            vchannel = am[1];
        }
        if (vip == "") {
            alert("未设置机房IP");
            return;
        }
        var objShell = new ActiveXObject("wscript.shell"); //创建客户端程序执行对象 
        try {
            objShell.Run("C:\\视频客户端\\RemoteView.exe " + vip + ":" + vchannel + ":3:");
            //objShell.Run("F:\STAY_SOFT\CM-desk_Manager\PreViewClient.exe IP：通道：用户名：密码"); 
            //调用Run命令执行exe程序，参数是一个exe文件的路径(注:这个路径是客户端电脑上的已知路径)。
            objShell = null;
        }
        catch (ex) {
            alert("请将文件下载到C:\\,并解压到该目录下!");
            window.open("http://192.168.129.15/web/视频客户端.rar", "", "");
        }
        return false;
    },
    setRelevance: function() {
        //设置节点与设备之间的关联
        MenuAction.destroyContextMenu(); //先将右键菜单销毁
    },
    getContextMenu: function(isDestroy) {
        //获取现在有右键菜单的节点
        var node = null;
        var group = _('group');
        var ggd = group.getAttribute('container');
        if (ggd.nodes) {
            var length = ggd.nodes.length;
            for (var i = 0; i < length; i++) {
                if (ggd.nodes[i].contextMenu) {//循环所有的点，如果该点的右键不为空
                    node = ggd.nodes[i];
                    if (isDestroy) {//如果参数不为空，就将右键菜单销毁
                        node.destroyContextMenu();
                    }
                    break;
                }
            }
        }
        if (ggd.shapes) {
            var length = ggd.shapes.length;
            for (var i = 0; i < length; i++) {
                if (ggd.shapes[i].contextMenu) {//循环所有的点，如果该点的右键不为空
                    node = ggd.shapes[i];
                    if (isDestroy) {//如果参数不为空，就将右键菜单销毁
                        node.destroyContextMenu();
                    }
                    break;
                }
            }
        }
        return node;
    },
    destroyContextMenu: function() {
        //菜单操作的基本项，销毁右键菜单
        MenuAction.getContextMenu(true);
    },
    showWindow: function(o, t) {
        //显示窗口
        //o 对象
        //t 类型
        if (!win) {
            //如果win为空，就创建
            win = new Window();
        }
        win.init(o, t);
        win.show();
    },
    //创建面板
    createFormPanel: function(tablename, id) {
        var columns = Topo_RoomPlaneRight.GetColumnsListByTableName(tablename).value;
        var itemsReader = [];
        var p_items = [];

        var length = columns.Rows.length;
        if (length > 0) {
            this.tablename = columns.Rows[0].QUERYFROMVIEW;
            for (var i = 0; i < length; i++) {
                p_items.push({
                    name: columns.Rows[i].ENFIELD,
                    fieldLabel: columns.Rows[i].CHFIELD
                });
                itemsReader.push({
                    name: columns.Rows[i].ENFIELD,
                    type: 'string'
                });
            }
        }
        var jReader = new Ext.data.JsonReader({
            root: 'data'
        }, itemsReader);
        return new Ext.FormPanel({
            id: id,
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            defaults: { width: 240, border: false, readOnly: true }, //disabled: true, 不能输入
            defaultType: 'textfield', //默认的input类型
            // height: 350,
            reader: jReader,
            items: p_items,
            labelSeparator: ':', //定义文字标签后的符号
            labelWidth: 100,
            labelAlign: 'right'
        });
    },
    createWindow: function(type, at) {
        var node = MenuAction.getContextMenu(true); //将右键菜单销毁的同时，返回该节点
        var group = _('group');
        var ggd = group.getAttribute('container');
        if (ggd.contextMenu) {
            ggd.destroyContextMenu();
            MenuAction.showWindow(ggd);
        }
        else {
            //如果节点不为null,而且节点的性能不为null,并且节点的性能id不为空,说明该节点已经关联到设备,可以查看节点的性能
            if (node && node.property && node.property.id) {
                //                if (resourcetypeData) {
                MenuAction.showWindow(node, type);
                //                }
                //                else {
                //                    Ext.Msg.alert('提示', '数据加载中，请稍后再试...'); //资源类型的数据没有加载完成，给予提示
                //                    return false;
                //                }
            }
            else {
                Ext.MessageBox.alert('提示', '该设备还没有关联到实际设备，请先设置关联或与管理员联系!');
            }
        }
    },
    /*
    *   对象绑定事件
    *   @param  target  对象
    *   @param  eventName   事件对象
    *   @param  handler 事件
    *   @param  argsObject  参数对象
    */
    attachevent: function(target, eventName, handler, argsObject) {
        var eventHandler = handler;
        if (argsObject) {
            eventHander = function(e) {
                handler.call(e, argsObject);
            }
        }
        if (window.attachEvent)//IE
            target.attachEvent("on" + eventName, eventHander, false);
        else//FF
            target.addEventListener(eventName, eventHander, false);
    },
    getAlaramLevel: function() {
        /*获取告警等级的数字,便于告警级别比较*/
        var am = arguments[0];
        var alaramLevel = 0; //默认等级最低为0(警告告警)
        switch (am) {
            case '次要告警':
                alaramLevel = 1;
                break;
            case '紧急告警':
                alaramLevel = 3;
                break;
            case '警告告警':
                alaramLevel = 0;
                break;
            case '主要告警':
                alaramLevel = 2;
                break;
            default:
                alaramLevel = -1; //告警等级为空
                break;
        }
        return alaramLevel;
    },
    getAlaramLevelColor: function() {
        /*获取不同等级告警颜色*/
        var am = arguments[0];
        var alaramColor = '#FF0000';
        switch (am) {
            case '次要告警':
                alaramColor = '#FDFF63';
                break;
            case '紧急告警':
                alaramColor = '#FF0000';
                break;
            case '警告告警':
                alaramColor = '#00FFFF';
                break;
            case '主要告警':
                alaramColor = '#FF9800';
                break;
            default:
                alaramColor = '#FF0000';
                break;
        }
        return alaramColor;
    }
};
//事件组
var GroupEvent = {
    mouseDown: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        //将事件点设置为选中状态
        //先清除所有的对象右键菜单
        document.selection.empty();
        ggd.point('down'); //将鼠标当前坐标设置为起始点
        ggd.eventStart();
        ggd.destroyContextMenu(); //将机房的右键菜单销毁
        //如果是右键，则弹出该机房的属性
        //如果选择对象为空，而且是鼠标右键就弹出机房右键菜单
        if (!(ggd.selectedObj.length) && window.event.button == 2) {
            ggd.createContextMenu();
            ggd.showContextMenu(); //显示右键菜单
        }
        return false;
    },
    mouseOver: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        document.selection.empty();
        return false;
    },
    mouseOut: function() {
        return false;
    },
    mouseMove: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        ggd.point('move'); //将鼠标当前坐标设置为起始点
        ggd.eventStart('move');
        return false;
    },
    mouseUp: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        if (ggd.action != null) {
            ggd.point('up');
            var selNode = ggd.getEventNode('up');
            switch (ggd.action.toLowerCase()) {
                case "nodedown":
                    //ggd.moveSelectedObjEnd();
                    break;
                case "drawline":
                    ggd.drawLineEnd(selNode);
                    break;
                case "moveline":
                    ggd.moveLineEnd(selNode);
                    break;
                case "blankdown":
                    ggd.drawMirrorNodeEnd();
                    break;
                case "txtBox":
                    ggd.selectedObj[0].moveEnd();
                    break;
                default:
            }
        }
        //ggd.setGroupArea();
        ggd.action = null;
        return false;
    },
    dblClick: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        var node = null;
        var isFind = false;
        var length = ggd.shapes.length;
        for (var i = 0; i < length; i++) {
            if (ggd.shapes[i].id == event.srcElement.id) {
                node = ggd.shapes[i];
                isFind = true;
                break;
            }
        }
        if (!isFind) {
            length = ggd.nodes.length;
            for (var i = 0; i < length; i++) {
                if (ggd.nodes[i].id == event.srcElement.id) {
                    node = ggd.nodes[i];
                    isFind = true;
                    break;
                }
            }
        }
        if (node && (node.type == '10020001' || node.type == 'TBS')) {//如果是基站，打开基站面板图
            OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + node.property.equiptype + '&equipid=' + node.property.id, 600, 630);
        }
        if (node && (node.type == '10020018' || node.type == 'LOOP4200')) {//如果是LOOP4200，打开LOOP4200面板图
            OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + node.property.equiptype + '&equipid=' + node.property.id, 1000, 400);
        }
        if (node && (node.type == '10020017' || node.type == 'LOOP3440')) {//如果是LOOP3440，打开LOOP3440面板图
            OpenModalDialog('EFaceplateWindow.aspx?equiptype=' + node.property.equiptype + '&equipid=' + node.property.id, 1000, 450);
        }
        if (node && (node.type == '10010001')) {//视频
            MenuAction.openVideo();
        }
    },
    onContextMenu: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        if ((ggd.nodes != null && ggd.nodes.length > 0) || (ggd.shapes != null && ggd.shapes.length > 0) || (ggd.lines != null && ggd.lines.length > 0)) {
            ggd.point('down');
            ggd.eventStart();
            ggd.setContextMenuShow();
        }
        GroupEvent.stopEvent();
        return false;
    },
    keyDown: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        if (window.event.ctrlKey)
            ggd.ctrlKey = true;
        switch (window.event.keyCode) {
            case 46: //删除键
                ggd.cannelSelected();
                break;
            case 65: //a字母键
                if (window.event.ctrlKey) {
                    ggd.selectAll();
                    ggd.multiSelect = true;
                    window.event.returnValue = false;
                }
                break;
            default:
        }
    },
    keyUp: function() {
        var group = _('group');
        var ggd = group.getAttribute('container');
        ggd.ctrlKey = false;
    },
    click: function() {
        // alert('单击事件触发');
        return false;
    },
    getX: function(x) {
        //获取事件点在界面中的横位置
        return (x + document.body.scrollLeft);
    },
    getY: function(y) {
        //获取事件点在界面中的纵位置
        return (y + document.body.scrollTop);
    },
    getMouseX: function() {
        //获取事件鼠标的横坐标
        return window.event.clientX;
    },
    getMouseY: function() {
        //获取事件鼠标的纵坐标
        return window.event.clientY
    },
    getXPosition: function(o) {
        //获取对象的左边距
        var x = o.offsetLeft;
        while (o = o.offsetParent) {
            x += o.offsetLeft;
        }
        return x;
    },
    stopEvent: function() {
        window.event.cancelBubble = true; //禁止事件冒泡
        window.event.returnValue = false; //屏蔽原鼠标事件
    },
    getYPosition: function(o) {
        //获取对象的上边距
        var y = o.offsetTop;
        while (o = o.offsetParent) {
            y += o.offsetTop;
        }
        return y;
    },
    isInArr: function(arr, s) {
        var res = false;
        if (arr) {
            var length = arr.length;
            for (var i = 0; i < length; i++) {
                if (arr[i] == s) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    },
    //将对象添加到数组
    insertObjInArr: function(arr, s) {
        if (!arr) {
            arr = [];
        }
        arr[arr.length] = s;
        return arr;
    },
    //将对象从数组中删除
    removeObjInArr: function(arr, s) {
        var tArr = null;
        var count = 0;
        if (arr) {
            tArr = [];
            var num = arr.length;
            for (var i = 0; i < num; i++) {
                if (arr[i] != s) {
                    tArr[count] = arr[i];
                    count++;
                }
            }
        }
        return tArr;
    }
};
/*
*   公共函数区
*/

/*
*   整个页面初始化
*/
function initPage() {
    var isFinish = false;
    /*屏蔽页面原始右键菜单*/
    window.document.body.oncontextmenu = function() {
        return false;
    };
    var roomid = getValueOfURLParamter('roomid');
    if (!roomid) {
        roomid = '2'; //默认为梧桐山机房 
    }
    var s = Topo_RoomPlaneRight.GetRoomEquipJSON(roomid).value;
    if (s) {
        AllObjects = JSON.parse(s);
        var group = new Group();
        group.init();
        group.initChild();
        win = new Window(); //创建窗口对象
    }
}

/*
*   获取工具条操作权限对象数组
*/
function getToolOperation() {
    ToolBarOperper = getXMLPropertyNodes(xmlPath, "//operations");
}

/*
*   显示告警
*/
function setAlarm() {
    var ggd = _('group').getAttribute('container');
    var node = null;
    var count = 0;
    /*先清除所有有告警信息的节点*/
    count = ggd.nodes.length;
    for (var j = 0; j < count; j++) {
        node = ggd.nodes[j];
        if (node.alarm.isalarm) {//只对存在告警的元素进行清除，减少操作
            node.clearAlarm();
        }
    }
    count = ggd.shapes.length;
    for (var j = 0; j < count; j++) {
        node = ggd.shapes[j];
        if (node.alarm.isalarm) {//只对存在告警的元素进行清除，减少操作
            node.clearAlarm();
        }
    }

    var data = Topo_RoomPlaneRight.GetAlarm(ggd.room.id, 'ROOM').value;
    if (data) {
        var length = data.Rows.length;
        for (var i = 0; i < length; i++) {
            count = ggd.nodes.length;
            for (var j = 0; j < count; j++) {
                node = ggd.nodes[j];
                if (!node.alarm.isalarm && node.property.id != '' && node.property.id == data.Rows[i]['OBJECTCODE']) {
                    node.setAlarm(data.Rows[i]);
                }
            }
            count = ggd.shapes.length;
            for (var j = 0; j < count; j++) {
                node = ggd.shapes[j];
                if (!node.alarm.isalarm && node.property.id != '' && node.property.id == data.Rows[i]['OBJECTCODE']) {
                    node.setAlarm(data.Rows[i]);
                }
            }
        }
    }
}
//setTimeout('getData()', 5000); //加载资源类型数据
//setInterval('setAlarm()', 180000); //半小时查询一次告警
setInterval('setAlarm()', 3000); //3秒钟查询一次告警
///*获取资源类型数据*/
//function getData() {
//    //设置数据解析数组
//    var readerType = [{ name: 'TYPEID' }, { name: 'TYPENAME' }, { name: 'TYPECNNAME' }, { name: 'TABLENAME' }, { name: 'REMARK' }, { name: 'TYPE' }, { name: 'SUBSYSTEMID' }, { name: 'ISDISPLAY' }, { name: 'ICO'}];
//    //创建数据存储器
//    var storeType = new Ext.data.Store({
//        proxy: new Ext.data.HttpProxy({ url: "Handler.ashx" }),
//        reader: new Ext.data.JsonReader({ root: 'data' }, new Ext.data.Record.create(readerType))
//    });
//    //初始化数据
//    storeType.load({
//        params: { tablename: "RESOURCETYPE", resourcetypeid: '0', where: ' where  typeid is not null', sort: ' typecnname', type: '' },
//        callback: function(records, options, success) {
//            resourcetypeData = records;
//        },
//        scope: storeType,
//        add: false
//    });
//}
///*获取资源名称*/
//function getResourceName(typeid) {
//    if (resourcetypeData) {
//        var length = resourcetypeData.length;
//        for (var i = 0; i < length; i++) {
//            if (typeid == resourcetypeData[i].data.TYPEID) {
//                return resourcetypeData[i].data.TYPECNNAME;
//                // break;
//            }
//        }
//    }
//    return '';
//}
/*获取资源对应表名*/
function getResourceTableName(typeid) {
    var rt = getServerData("Handler2.ashx?tablename=RESOURCETYPE&where=typeid='" + typeid + "'");
    if (rt.length > 0) {
        var rto = JSON.parse(rt);
        return rto[0]["TABLENAME"];
    }
    return '';
}